package com.example.file_demo.controller;

import com.example.file_demo.config.HccCommonConfig;
import com.example.file_demo.util.FileUploadUtil;
import com.example.file_demo.util.PathUtils;
import com.example.file_demo.util.ZipUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    // 上传文件的保存路径（可以根据需要修改）
    private static final String UPLOAD_DIR = "D:\\idea-workspace";

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("files") List<MultipartFile> files) {
        if (files.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No files to upload");
        }

        List<String> fileNames = FileUploadUtil.saveFiles(files);

        // 返回上传的文件名列表
        return ResponseEntity.ok("Uploaded files: " + String.join(", ", fileNames));
    }

    @PostMapping("/saveFilesForEach")
    public ResponseEntity<String> saveFilesForEach(@RequestParam("files") List<MultipartFile> files) throws IOException {
        if (files.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No files to upload");
        }

        Map<String, File> map = FileUploadUtil.saveFilesForEach(files);
        map.forEach((s, s2) -> {
            System.out.println(s+"======================="+ PathUtils.getRelativePath(HccCommonConfig.getProfile(), s2.getAbsolutePath()));
        });
        // 返回上传的文件名列表
        return null;
    }

    @PostMapping("/uploadZip")
    public void uploadZipFile(@RequestParam("zipFile") MultipartFile file) {
        try {
            System.out.println(file.getOriginalFilename());
            ZipUtils.unzip(FileUploadUtil.getFileInputStreamFromMultipartFile(file), UPLOAD_DIR);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
